import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import redirectRoutes from './redirect'

// 公共路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true,
    meta: { title: 'login.title' }
  },
  {
    path: '/404',
    component: () => import('@/views/error-page/404'),
    hidden: true,
    meta: { title: 'errorPage.notFound' }
  },
  {
    path: '/profile',
    component: () => import('@/layouts/backend/index'),
    hidden: true,
    children: [
      {
        path: '',
        name: 'Profile',
        component: () => import('@/views/profile/index'),
        meta: { title: 'navbar.profile', icon: 'User' }
      }
    ]
  },
  {
    path: '/',
    component: () => import('@/layouts/backend/index'),
    redirect: '/dashboard',
    meta: { title: 'menu.dashboard', icon: 'House' },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index'),
        meta: { title: 'menu.dashboard', icon: 'House', keepAlive: true }
      }
    ]
  },
  // 货物管理
  {
    path: '/shipment',
    component: () => import('@/layouts/backend/index'),
    redirect: '/shipment/list',
    meta: { title: 'menu.shipmentManagement', icon: 'Van' },
    children: [
      {
        path: 'list',
        name: 'ShipmentList',
        component: () => import('@/views/shipment/list'),
        meta: { title: 'menu.shipmentList', icon: 'List', keepAlive: true }
      },
      {
        path: 'detail/:id',
        name: 'ShipmentDetail',
        component: () => import('@/views/shipment/detail'),
        meta: { title: 'menu.shipmentDetail', activeMenu: '/shipment/list' },
        hidden: true
      },
      {
        path: 'route/:id',
        name: 'ShipmentRoute',
        component: () => import('@/views/shipment/route'),
        meta: { title: 'menu.shipmentRoute', activeMenu: '/shipment/list' },
        hidden: true
      }
    ]
  },
  // 系统管理
  {
    path: '/system',
    component: () => import('@/layouts/backend/index'),
    redirect: '/system/user',
    meta: { title: 'menu.system', icon: 'Setting', roles: ['admin'] },
    children: [
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/system/user'),
        meta: { title: 'menu.user', icon: 'User', roles: ['admin'], keepAlive: true }
      },
      {
        path: 'api-config',
        name: 'ApiConfig',
        component: () => import('@/views/system/api-config'),
        meta: { title: 'menu.apiConfig', icon: 'Link', roles: ['admin'], keepAlive: true }
      },
      {
        path: 'sys-config',
        name: 'SysConfig',
        component: () => import('@/views/system/sys-config'),
        meta: { title: 'menu.sysConfig', icon: 'Setting', roles: ['admin'], keepAlive: true }
      }
    ]
  },
  // 404页面必须放在末尾
  { path: '/:pathMatch(.*)*', redirect: '/404', hidden: true }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...constantRoutes, ...redirectRoutes],
  scrollBehavior: () => ({ top: 0 })
})

// 白名单路径，不需要登录即可访问
const whiteList = ['/login', '/404']

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 货物监控系统` : '货物监控系统'
  
  // 获取用户信息
  const hasToken = getToken()
  
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，重定向到首页
      next({ path: '/' })
    } else {
      const userStore = useUserStore()
      const hasRoles = userStore.roles && userStore.roles.length > 0
      if (hasRoles) {
        // 检查用户是否有访问当前路由的权限
        if (hasPermission(to, userStore.roles)) {
          next()
        } else {
          next('/404')
        }
      } else {
        try {
          // 获取用户信息
          const { roles } = await userStore.getInfo()
          
          // 基于角色判断是否有权限访问
          if (hasPermission(to, roles)) {
            next({ ...to, replace: true })
          } else {
            next('/404')
          }
        } catch (error) {
          // 清除用户信息，重定向到登录页
          await userStore.resetToken()
          ElMessage.error(error.message || '验证失败，请重新登录')
          next(`/login?redirect=${encodeURIComponent(to.path)}`)
        }
      }
    }
  } else {
    // 没有令牌
    if (whiteList.includes(to.path)) {
      // 在白名单中，直接访问
      next()
    } else {
      // 重定向到登录页
      next(`/login?redirect=${encodeURIComponent(to.path)}`)
    }
  }
})

/**
 * 检查是否有权限访问路由
 * @param {Object} route 路由对象
 * @param {Array} roles 角色列表
 * @returns {Boolean}
 */
function hasPermission(route, roles) {
  if (route.meta && route.meta.roles) {
    // 如果路由有roles字段，检查用户角色是否包含
    return route.meta.roles.some(role => roles.includes(role))
  } else {
    // 没有roles字段的路由所有人都可访问
    return true
  }
}

export default router